/**
* @Description: 客户管理修改
* @author  qgj
* @date 
*/
<template>
  <div class="app-container">
    <div style="padding:20px">
        <div style="margin-bottom:16px">
            <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
            <span style="display: inline-block;font-weight: 500;color: #333333;font-size: 16px;">客户详情</span>
        </div>
        <el-descriptions class="margin-top" :column="3" border>
            <el-descriptions-item labelStyle="width: 150px" contentStyle="width: 250px" label="ERP客户编号">{{customerDetail.code}}</el-descriptions-item>
            <el-descriptions-item labelStyle="width: 150px" contentStyle="width: 250px" label="客户名称">{{customerDetail.name}}</el-descriptions-item>
            <el-descriptions-item labelStyle="width: 150px" contentStyle="width: 250px" label="客户分类">{{ getCustomerType(customerDetail.type) }}</el-descriptions-item>
            <el-descriptions-item label="ERP使用状态">{{customerDetail.erpStatus == '00'?'可用':customerDetail.erpStatus == '01'?'禁用':'反审核中'}}</el-descriptions-item>
            <el-descriptions-item label="统一社会信用代码">{{customerDetail.creditCode}}</el-descriptions-item>
            <el-descriptions-item label="电子邮箱">{{customerDetail.email}}</el-descriptions-item>
            <el-descriptions-item label="行政区划">{{customerDetail.divisionName}}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{customerDetail.contactName}}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{customerDetail.contactMobile}}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{customerDetail.address}}</el-descriptions-item>
            <el-descriptions-item label=""></el-descriptions-item>
            <el-descriptions-item label=""></el-descriptions-item>
            <!-- <el-descriptions-item v-for="item in descriptions" :key="item.value" :label="item.label">{{item.value}}</el-descriptions-item> -->
        </el-descriptions>
        <div style="margin:16px 0 ">
            <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
            <span class="top_title">开票信息</span>
        </div>
        <el-descriptions class="margin-top" :column="3" border>
            <el-descriptions-item  labelStyle="width: 150px" contentStyle="width: 250px" label="开户行">{{customerDetail.bank}}</el-descriptions-item>
            <el-descriptions-item  labelStyle="width: 150px" contentStyle="width: 250px" label="开户行账号">{{customerDetail.account}}</el-descriptions-item>
            <el-descriptions-item  labelStyle="width: 150px" contentStyle="width: 250px" label=""></el-descriptions-item>
        </el-descriptions>
        <div style="width:100%;height:20px"></div>
        <div style="margin-bottom:16px">
            <span style="display: inline-block; color: #333333; font-size: 14px;">编辑信息</span>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="客户状态" prop="status">
                        <el-select v-model="form.status" placeholder="请选择" style="width:100%" clearable>
                            <el-option
                                v-for="item in dict.type.basic_data_customer_system_status"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="结算方式" prop="settlement">
                        <el-select v-model="form.settlement" placeholder="请选择" style="width:100%" clearable>
                            <el-option
                                v-for="item in dict.type.basic_data_customer_settlement"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="授权协议号" prop="licenseAgreementNumber">
                        <el-input v-model="form.licenseAgreementNumber" placeholder="请输入" maxlength="30" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="订单类型" prop="supportOrderTypes">
                        <el-select v-model="form.supportOrderTypes" multiple collapse-tags placeholder="请选择" style="width:100%" clearable>
                          <el-option
                              v-for="item in dict.type.order_type"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="归属业务部门" prop="businessDeptId">
                        <el-cascader
                            style="width:100%"
                            :value="editShowValue"
                            :options="deptOptions"
                            :props="defaultProps"
                            ref="refHandle"
                            @change="handleChange">
                        </el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="归属业务人员" prop="businessUserId">
                        <el-select v-model="form.businessUserId" placeholder="请选择" style="width:100%" clearable>
                            <el-option
                                v-for="item in businessOptions"
                                :key="item.userId"
                                :label="item.nickName"
                                :value="item.userId"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="驿站合作模式" prop="stationCooperationMode">
                        <el-select v-model="form.stationCooperationMode" multiple placeholder="请选择" style="width:100%" clearable>
                            <el-option
                                v-for="item in dict.type.basic_data_customer_station_cooperation_mode"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="驿站结算方式" prop="stationSettlements">
                        <el-select v-model="form.stationSettlements" placeholder="请选择" style="width:100%" clearable>
                            <el-option
                                v-for="item in dict.type.basic_data_customer_station_settlement"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="手续费费率(‰)" prop="handlingFeeRate">
                  <el-input v-model="form.handlingFeeRate" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6"></el-col>
              <el-col :span="6"></el-col>
              <el-col :span="6"></el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="备注">
                    <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 12}" type="textarea" maxlength="500" show-word-limit placeholder="请输入内容"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="经营场所照片">
                        <el-upload
                            :action="uploadImgUrl"
                            accept=".png, .jpg"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-success="handleAvatarSuccess"
                            :file-list="imageList"
                            :headers="headers"
                            :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        
        <div style="margin-bottom:20px">
            <!-- <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span> -->
            <span style="display: inline-block; color: #333333; font-size: 14px;">合同信息</span>
            <el-button style="float:right" type="primary" size="small" icon="el-icon-upload2" @click="handleImport">上传合同附件</el-button>
        </div>
        <el-table 
            v-loading="loading" 
            :data="contractList" 
            height="300"
            @selection-change="handleSelectionChange"
        >
            <el-table-column label="序号" type="index" width="60" align="left" />
            <el-table-column label="合同编号" prop="code" width="160" />
            <el-table-column label="文件名称" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{scope.row.contractFile?scope.row.contractFile.objectOriginalName:''}}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="left" prop="status" width="100">
              <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="上传人员" :show-overflow-tooltip="true" width="150">
                <template slot-scope="scope">
                    <span>{{scope.row.contractFile?scope.row.contractFile.uploadUserName:''}}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
            <template slot-scope="scope">
                <el-button
                size="mini"
                type="text"
                @click="handleExport(scope.row)"
                v-if="scope.row.id"
                v-hasPermi="['system:role:edit']"
                >下载</el-button>
                <el-button
                size="mini"
                type="text"
                v-else
                @click="onRemove(scope.row)"
                v-hasPermi="['system:role:remove']"
                >删除</el-button>
            </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="h84_line"></div>
    <div class="bottom-btn">
        <div class="bottom-locate" >
          <el-button type="default" @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </div>

    <!-- 合同上传对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="600px" append-to-body>
        <el-upload
            ref="upload"
            :limit="1"
            :headers="upload.headers"
            :action="upload.url + '&updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :before-upload="handleBeforeUpload"
            :auto-upload="true"
            drag
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
            <div style="text-align: left;"><span>请上传合同附件，10M以内。</span></div>
            </div>

        </el-upload>
        <div style="width:100%;height:20px"></div>
        <el-form ref="queryModel" :model="queryModel" :rules="rules" label-width="80px">
            <el-form-item label="合同编号" prop="code">
                <el-input v-model="queryModel.code" placeholder="请输入" maxlength="50" />
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="queryModel.remark" :autosize="{ minRows: 2, maxRows: 12}" type="textarea" maxlength="500" show-word-limit placeholder="请输入内容"></el-input>
            </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QueryTableRender from "@/components/QueryTableRender";
import { listCustomer, getCustomer, updateCustomer, getDeptTree, getBusiness } from "@/api/basic/customer";
// import {getOrderTerminalList} from "@/api/costManagement";
// import DialogCostEdit from "@/views/costManagement/components/DialogCostEdit";
// import dayjs from "dayjs"
import { getToken } from "@/utils/auth";
import ImageUpload from "@/components/ImageUpload"; // 图片上传组件

export default {
  name: "CustomerManageEdit",
  dicts: ['basic_data_customer_type','basic_data_customer_system_status','basic_data_customer_erp_status','order_type',
  'basic_data_customer_settlement','business_yes_no','basic_data_customer_station_cooperation_mode','basic_data_customer_station_settlement'],
  components: {QueryTableRender},
  data() {
    return {
      form: {},
      queryModel:{},
      rules:{
        businessDeptId:[
          { required: true, message: '请选择归属业务部门', trigger: 'change' }
        ],
        code: [
          { required: true, message: "合同编号不能为空", trigger: "blur" },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        stationCooperationMode:[
          { required: true, message: '请选择驿站合作模式', trigger: 'change' }
        ],
        stationSettlements:[
          { required: true, message: '请选择驿站结算方式', trigger: 'change' }
        ],
        handlingFeeRate:[
          { pattern: /^\d{1,3}(\.\d{1,2})?$/, message: '请输入0-1000内的数字(最多2位小数)'}
        ]
      },
      editVisible: false,
      curRecord: null,
      customerValue: [], //  价目数据
      customerData: [],
      loading:false,
      height:200,
      contractList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      dialogImageUrl: '',
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/obs/upload?businessTable=basic_data_customer", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      imageList:[], //上传图片
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/obs/upload?businessTable=basic_data_customer_contract"
      },
      total:0,
      customerDetail:{},//详情获取
      deptOptions:[], //部门tree
      defaultProps: {
        children: "children",
        label: "label",
        value: "id",
        checkStrictly: true
      },
      businessOptions:[],//归属人员
      contracts:{},
      fileList:[],
      editShowValue:[]
    }
  },
  created() {
    this.getCustomerDetail();
    console.log(this.$store.getters.level,'12321',this.$store.getters.templateId)
  },
  activated() {
    // this.tableHeight();
  },
  updated() {
    // console.log(this.$store.getters.level,'12321',this.$store.getters.templateId)
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    // this.tableHeight();
    // this.$nextTick(() => {
    //   this.$refs.filterTable.doLayout();
    // });
  },
  watch: {
    $route() {
        // location.reload();
        this.getCustomerDetail();
    },
    // businessDeptId() {
    //   if (this.$refs.refHandle) {
    //     this.$refs.refHandle.dropDownVisible = false; //监听值发生变化就关闭它
    //   }
    // }
  },
  methods: {
    tableHeight() {
      this.$nextTick(() => {
        let height = document.body.clientHeight - 90 - 40;
        // 查询表单高度
        let s_height = document.getElementById('searchForm').clientHeight;
        // 按钮容器高度
        let btns_height = document.getElementById('comTabel').clientHeight;
        // 计算表格的高度
        this.height = height - s_height - btns_height - (this.total > 0 ? 60 : 0);
      });
    },
    // 表单重置
    reset() {
      this.imageList = [];
      this.form = {
        settlement: 'CURRENT_SETTLEMENT',  // 结算方式
        licenseAgreementNumber: undefined, // 授权协议号
        supportOrderTypes: undefined, // 订单类型
        // supportedBuyout: 'false',
        // roleSort: 0,
        status: 'VALID', // 客户状态
        businessDeptId: undefined, // 归属业务部门
        businessUserId: undefined, // 归属业务人员
        remark: undefined, // 备注
        businessPremisesPhotoIdList:[], // 经营场所照片
        stationCooperationMode: [], // 驿站合作模式
        stationSettlement: [], // 驿站结算方式
        stationSettlements: undefined, // 驿站结算方式
        handlingFeeRate: undefined, // 手续费费率
      };
      this.queryModel = {
        code: undefined,
        remark: undefined
      }
      this.resetForm("form");
    },
    /** 获取客户详情 */
    getCustomerDetail() {
        console.log(this.$route.query.customerId)
        if(this.$route.query.customerId){
            this.reset();
            const str = {
                customerId:JSON.parse(this.$route.query.customerId)
            }
            getCustomer(str).then(response => {
                this.getBusinessList(response.data.businessDeptId);
                this.customerDetail = response.data;
                this.form = response.data;
                this.$set(this.form,'stationSettlements',response.data.stationSettlement?response.data.stationSettlement[0]:undefined)
                // this.form.stationSettlements = response.data.stationSettlement?response.data.stationSettlement[0]:undefined
                // this.form.businessDeptId = [this.form.businessDeptId];
                this.editShowValue = this.form.businessDeptIds
                this.form.businessPremisesPhotoIdList = [];
                this.contractList = response.data.basicDataCustomerContractList;
                this.imageList = response.data.businessPremisesPhotoList;
                for(let i=0;i<this.imageList.length;i++){
                    this.imageList[i].url = process.env.VUE_APP_BASE_API + '/obs/download?id=' + this.imageList[i].id
                    this.form.businessPremisesPhotoIdList.push(this.imageList[i].id)
                }

                console.log(this.form)
            });
            getDeptTree().then(response => {
                this.deptOptions = response.data
            });
        }
        
    },
    //点击所属部门
    handleChange(val) {
        console.log(val)
        this.form.businessUserId = undefined;
        const value = val[val.length-1]
        this.form.businessDeptId = value
        this.getBusinessList(value)
    },
    //获取所属人员
    getBusinessList(val) {
        console.log(val)
        getBusiness({deptId:val}).then(response => {
            this.businessOptions = response.data
        });
    },
    handleSelectionChange() {},
    /** 上传图片成功操作 */
    handleAvatarSuccess(response, file, fileList) {
      // response表示上传结果
      // file表示当前上传的文件
      // fileList表示当前成功上传的图片数组
      // 将图片保存
      console.log(response,file,fileList,this.form)
    //   let arr = [];
      this.form.businessPremisesPhotoIdList=[];
      for(let i=0;i<fileList.length;i++){
        if(fileList[i].response){
            this.form.businessPremisesPhotoIdList.push(fileList[i].response.data.id)
        }else{
            this.form.businessPremisesPhotoIdList.push(fileList[i].id)
        }
      }
    //   arr.push(response.data.id)
    //   this.form.businessPremisesPhotoIdList=[];
      this.form.businessPremisesPhotoIdList.push(response.data.id)
      this.imageList = fileList
    //   console.log(this.form.businessPremisesPhotoIdList)
    },
    /** 上传图片删除操作 */
    handleRemove(file, fileList) {
        // console.log(file, fileList,this.imageList);
        this.form.businessPremisesPhotoIdList=[]
        for(let i=0;i<fileList.length;i++){
            if(fileList[i].response){
                this.form.businessPremisesPhotoIdList.push(fileList[i].response.data.id)
            }else{
                this.form.businessPremisesPhotoIdList.push(fileList[i].id)
            }
        }
    },
    handlePictureCardPreview(file) {
        console.log(file)
        if(file.response){
          this.dialogImageUrl = process.env.VUE_APP_BASE_API + '/obs/download?id=' + file.response.data.id;
        }else{
          this.dialogImageUrl = process.env.VUE_APP_BASE_API + '/obs/download?id=' + file.id;
        }
        this.dialogVisible = true;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "上传合同附件";
      this.upload.open = true;
      this.queryModel.code = undefined;
      this.queryModel.remark = undefined;
      if(this.fileList.length != 0){
        this.$refs.upload.clearFiles();
      }
      
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传前处理 */
    handleBeforeUpload(file) {
      const isLt = file.size / 1024 / 1024 < 10;
      if (!isLt) {
        this.$modal.msgError(`文件大小不能超过10MB!`);
        return false;
      }
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.contracts = {
        contractFile:{
          objectOriginalName:response.data.objectOriginalName,
          uploadUserName:response.data.uploadUserName,
        },
        contractFileId:response.data.id
      }
      this.fileList.push(response)
    //   this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 合同状态修改
    handleStatusChange(row) {
        console.log(row)
    },
    /** 下载按钮操作 */
    handleExport(val) {
        console.log(val)
        const prop ={
            id:val.contractFile.id
        }
      this.downloadFile('/obs/download', prop,`${val.contractFile.objectOriginalName}`)
    },
    //删除合同
    onRemove(row) {
        // window.open("https://view.xdocin.com/view?src=" + val.)
      this.contractList.splice(this.contractList.indexOf(row), 1);
        
    },
    submitFileForm() {
        console.log(this.fileList)
        if(this.fileList.length == 0){
            this.$modal.msgWarning("合同附件不能为空")
            return
        }
        this.$refs["queryModel"].validate(valid => {
          if (valid) {
            let arr = {
              contractFile:{
                objectOriginalName:this.contracts.contractFile.objectOriginalName,
                uploadUserName:this.contracts.contractFile.uploadUserName,
              },
              contractFileId:this.contracts.contractFileId
            }
              this.upload.open = false;
              arr.code = this.queryModel.code;
              arr.remark = this.queryModel.remark;
              arr.status = true;
              this.contractList.push(arr);
              console.log(this.contractList,this.contracts)
          }
        });
        
        // this.contractList.push()
    },
    //提交
    submitForm() {
        this.$refs["form"].validate(valid => {
        if (valid) {
            this.form.stationSettlement = [];
            this.form.stationSettlement.push(this.form.stationSettlements)
            const str = this.form;
            str.basicDataCustomerContractList = this.contractList;
            // str.businessDeptId = str.businessDeptId[str.businessDeptId.length-1]
            updateCustomer(str).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
            });
        }
      });
    },
    /** 取消 */
    cancel() {
    //   this.$router.go(-1)
    //   this.$destroy('CustomerManageEdit')
      const obj = { path: "/basicData/customerManage" };
      this.$tab.closeOpenPage(obj);
    },
    

    /**
     * 客户分类
     * @param {*} value 
     */
    getCustomerType(value) {
      console.log(value)
      let show = '';
      this.dict.type.basic_data_customer_type.some((item) => {
        if (value == item.value) {
          show = item.label;
          return true;
        }
      });
      return show;
    },
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-upload-dragger{
  // margin-left: 18%!important;
  width: 558px;
}
// ::v-deep .el-upload__tip text-center {
//   text-align: left;
// }

/* 注意此处不能有scoped 否则样式无法生效 */
// .el-cascader-panel{
//   .el-radio__inner{
//     border: 0px;
//     background:transparent;
//   }
//   .el-radio__input.is-checked .el-radio__inner{
//     background:none;
//   }
//   .el-radio{
//     height: 100%;
//     width: 150px;
//     position: absolute;
//     z-index: 10;
//   }
// }
</style>